#!/bin/sh
#
# dvd2ogm.sh INPUT.ISO TITLE
#

tc_input="$1"
tc_title="$2"
tc_audio=0
tc_bitrate=1024
tc_keyfrms=50
tc_vorbisq=5
tc_fps=25
tc_divxlog="./divx4.log"
xvidconf="./xvid4.cfg"
outfile="./out.ogm"


transcode_common()
{
	transcode -H 10 -a $tc_audio -T $tc_title,-1 -x dvd \
		-i "$tc_input" \
		-w $tc_bitrate,$tc_keyfrms \
		--a52_drc_off \
		-b 0,1,$tc_vorbisq \
		-J smartyuv=threshold=10:Blend=1:diffmode=2:highq=1 \
		-f $tc_fps \
		--export_par 106,100 \
		--progress_meter 1 --progress_rate $tc_fps \
		$@
}

transcode_pass1()
{
	echo "Starting encoding pass 1 ..."
	transcode_common -R "1,$tc_divxlog" -y xvid,ogg -o /dev/null -m "$outfile.audio"
	echo "Pass 1 done."
}

transcode_pass2()
{
	echo "Starting encoding pass 2 ..."
	transcode_common -R "2,$tc_divxlog" -y xvid,null -o "$outfile.video"
	echo "Pass 2 done."
}

ogg_merge()
{
	ogmmerge -o "$outfile" "$outfile.audio" "$outfile.video"
}

mkxvidconf()
{
	cat << EOF
##############################################
#                                            #
# Configuration file for XviD 1.0.0 (API-4)  #
#                                            #
# Generated by xvid4conf v1.12                #
#                                            #
##############################################



#
# Feature settings
#

[features]
quant_type = h263
motion = 6
chromame = 1
vhq = 1
max_bframes = 2
bquant_ratio = 150
bquant_offset = 100
bframe_threshold = 0
quarterpel = 0
gmc = 0
trellis = 0
packed = 1
closed_gop = 1
interlaced = 0
cartoon = 0
hqacpred = 1
frame_drop_ratio = 0
stats = 0
greyscale = 0
turbo = 0


#
# Quantizer settings
#

[quantizer]
min_iquant = 2
max_iquant = 31
min_pquant = 2
max_pquant = 31
min_bquant = 2
max_bquant = 31
#quant_intra_matrix = 
#quant_inter_matrix = 


#
# CBR settings
#

[cbr]
reaction_delay_factor = 16
averaging_period = 100
buffer = 100


#
# VBR settings
#

[vbr]
keyframe_boost = 0
overflow_control_strength = 5
curve_compression_high = 0
curve_compression_low = 0
max_overflow_improvement = 5
max_overflow_degradation = 5
kfreduction = 20
kfthreshold = 1
container_frame_overhead = 24
EOF
}

clean()
{
	rm -f "$tc_divxlog" "$xvidconf" "$outfile.video" "$outfile.audio"
}

set -e
[ -e "$outfile" ] && { echo "outfile exists"; exit 1; }
clean
mkxvidconf > "$xvidconf"
transcode_pass1
transcode_pass2
ogg_merge
clean

exit 0
